<template>
  <div id="app">

    <div id="admin">
      <div class="pos" v-loading="loading">
        <h1 class="adminh1">进销存管理系统</h1>
        <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            v-if="!status"
        >
          <el-form-item label="用户名：" prop="pass">
            <el-input
                prefix-icon="el-icon-user"
                style="width: 250px"
                type="text"
                v-model="ruleForm.pass"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密 码：" prop="checkPass">
            <el-input
                prefix-icon="el-icon-menu"
                style="width: 250px"
                show-password
                type="password"
                v-model="ruleForm.checkPass"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-col :span="12">
              <el-button type="primary" plain @click="resetForm('ruleForm')">重置</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" plain @click="submitForm('ruleForm')">登录</el-button>
            </el-col>
          </el-form-item>
        </el-form>

        <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            v-if="status"
        >
          <el-form-item label="电话号码：" prop="phoneNumber">
            <el-input
                prefix-icon="el-icon-user"
                style="width: 250px"
                type="text"
                v-model="ruleForm.phoneNumber"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码：" prop="code">
            <el-input
                prefix-icon="el-icon-menu"
                style="width: 130px"
                type="text"
                v-model="ruleForm.code"
                autocomplete="off"
            ></el-input>
            <el-button type="primary" @click="getCode('ruleForm')">获取验证码</el-button>
          </el-form-item>
          <el-form-item>
            <el-col :span="12">
              <el-button type="primary" plain @click="resetForm('ruleForm')">重置</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" plain @click="loginByPhone('ruleForm')">登录</el-button>
            </el-col>
          </el-form-item>
        </el-form>

        <div style="text-align: center;">
          <a href="javascript:0" v-if="status" @click=" this.status =false"
             style="color: #c5c3c3; text-decoration: none">通过用户名、密码登录</a>
          <a href="javascript:0" v-if="!status" @click=" this.status =true"
             style="color: #c5c3c3; text-decoration: none">通过电话、验证码登录</a>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name: "app",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户信息"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("长度至少为6位!"));
      } else {
        callback();
      }
    };
    var validatePhoneNumber = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!/^[1]([3-9])[0-9]{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    var validateCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (!/[0-9]{4}/.test(value)) {
        callback(new Error("验证码为4位数字!"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      checkCode: '',
      ruleForm: {
        pass: "",
        checkPass: "",
        phoneNumber: '',
        code: ''
      },
      status: false,
      rules: {
        pass: [{validator: validatePass, trigger: "blur"}],
        checkPass: [{validator: validatePass2, trigger: "blur"}],
        phoneNumber: [{validator: validatePhoneNumber, trigger: ["blur", "change"]}],
        code: [{validator: validateCode, trigger: ["blur", "change"]}]
      },
    };
  },
  methods: {
    loginByPhone(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.code == this.checkCode) {
            let param = new URLSearchParams()
            param.append("phoneNumber", this.ruleForm.phoneNumber);
            axios.post("/api/user/loginByPhoneNumber", param).then(response => {
              this.loading = false
              if (response.data != null && response.data != '') {
                localStorage.setItem("list", response.data);
                this.$router.push("/pig");
              } else {
                ElMessage.error("手机号码不存在")
              }
            })
          } else {
            ElMessage.error("验证码有误")
          }
        } else {
          ElMessage.error("请输入正确的验证码")
        }
      });
    },
    getCode(formName) {
      this.$refs[formName].validateField(['phoneNumber'], (valid) => {
        if (valid) {
          let param = new URLSearchParams();
          param.append("phoneNumber", this.ruleForm.phoneNumber);
          axios.post("/api/user/getCode", param).then(response => {
            if (response.data != null && response.data != '') {
              this.checkCode = response.data;
            } else {
              ElMessage.error("手机号不存在")
            }
          })
        } else {
          ElMessage.error("请输入正确的手机号")
        }
      });

    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          let param = {
            "userName": this.ruleForm.pass,
            "passWord": this.ruleForm.checkPass
          };
          axios.post('/api/user/userLogin', param).then(response => {
            this.loading = false
            if (response.data != null && response.data != '') {
              localStorage.setItem("list", response.data);
              this.$router.push("/pig");
            } else {
              alert('用户名密码错误');
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
};
</script>

<style>
* {
  padding: 0;
  margin: 0;
}

body {
  /*background: rgb(135, 206, 235);*/
}

#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

#admin {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -200px;
  margin-left: -250px;
  width: 500px;
  height: 400px;
  background: #fff;
  border-radius: 10%;
  box-shadow: 8px 10px 10px rgb(177, 223, 242);
}

.adminh1 {
  margin: 20px 0;
  text-shadow: 10px 13px 3px rgb(207, 207, 207);
  text-align: center;
}

.pos {
  width: 450px;
  height: 350px;
  position: absolute;
  top: 25px;
  left: 25px;
}
</style>